//
//  ViewController.m
//  喜马拉雅FM
//
//  Created by dllo on 16/1/22.
//  Copyright © 2016年 lanou.com. All rights reserved.
//

#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height

#import "ViewController.h"
#import "NetworkHandler.h"
#import "NetworkHandlerBlock.h"

#import "ModelForData.h"
#import "CollectionViewCell.h"

#import "ModelForCollectionViewTwo.h"
#import "CollectionCellTwo.h"

#import "ModelForCollectionFour.h"
#import "CollectionCellFour.h"

#import "ModelForCollectionViewFive.h"
#import "CollectionCellFive.h"

#import "MoreInformationViewController.h"
#import "SearchViewController.h"

#import <MJRefresh.h>

@interface ViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,NetworkHandlerDelegate>

@property (nonatomic, retain) UICollectionView *collection;
@property (nonatomic, retain) UIView *viewForRedLine;
@property (nonatomic, retain) NSMutableArray *arrForDataOfCollectionViewOne;
@property (nonatomic, retain) NSMutableArray *arrForDataOfCollectionViewTwo;
@property (nonatomic, retain) NSMutableArray *arrForDataOfCollectionViewFour;
@property (nonatomic, retain) NSMutableArray *arrForDataOfCollectionViewFive;
@property (nonatomic, assign) CGFloat redX;

@end

@implementation ViewController

- (void)dealloc {
    
    [_collection release];
    [_viewForRedLine release];
    [_arrForDataOfCollectionViewOne release];
    [_arrForDataOfCollectionViewTwo release];
    [_arrForDataOfCollectionViewFour release];
    [_arrForDataOfCollectionViewFive release];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [super dealloc];
    
}

#pragma mark VC的生命周期.
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];

    // 喜马拉雅首页.
    self.navigationItem.title = @"喜马拉雅FM";
    // 添加搜索按钮.
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(handleSearchAction:)];
    // 给搜索按钮的颜色设置为灰色,默认为蓝色.
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor grayColor];

    // 将scrollView的上下左右偏移关闭.
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.automaticallyAdjustsScrollViewInsets = NO;
    
    // 注册通知中心.
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(handleCenter:) name:@"XiaoBianTuiJian" object:nil];
    
    
    [self handleDataForCollectionViewOne];
    [self handleDataForCollectionViewTwo];
    [self handleDataForCollectionViewFour];
    [self handleDataForCollectionViewFive];
    [self createTitleView];
    [self createRedLine];
    [self creatCollectionView];
    [self createKVO];
    
//    self.collection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self handleDataForCollectionViewOne];
//        [self handleDataForCollectionViewTwo];
//        [self handleDataForCollectionViewFour];
//        [self handleDataForCollectionViewFive];
//        
//    }];
//    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        // 进入刷新状态后会自动调用这个block
//    }];
//    或
//    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
//    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
//    
//     马上进入刷新状态
//    [self.collection.mj_header beginRefreshing];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(internet) name:@"InternetIsNo" object:nil];
}

// 内存警告.
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)internet {

    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请检查一下你的网络,并且重新启动一下程序" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
//     UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark 点击方法的实现.
// 导航栏上"搜索"推出的搜索页面.
- (void)handleSearchAction:(UIBarButtonItem *)searchButtonItem {

    SearchViewController *search = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:search animated:YES];
}

// 小编推荐中"更多"的点击方法.推出小编推荐更多的页面.
- (void)handleCenter:(NSNotificationCenter *)center {

    MoreInformationViewController *moreInformation = [[MoreInformationViewController alloc]init];
    moreInformation.navigationItem.title = @"小编推荐";
    [self.navigationController pushViewController:moreInformation animated:NO];

}

// 首页上小红线及collection界面随button的点击方法实现切换.
- (void)handleAction:(UIButton *)button {
    
    if (button.frame.origin.x != self.viewForRedLine.frame.origin.x) {

        [UIView animateWithDuration:0.5 animations:^{

            self.redX = button.frame.origin.x;
            self.viewForRedLine.transform = CGAffineTransformMakeTranslation(self.redX, 0);
         
        }];
        // collection加动画的话能看见黑页面.
           self.collection.contentOffset = CGPointMake(self.redX * 4, 0);
        
    }
}

#pragma mark 数据处理.

#pragma mark ** 采用代理模式回调.
- (void)handleDataForCollectionViewOne {
 
//    [NetworkHandler handlerJSONWithURL:@"http://mobile.ximalaya.com/mobile/discovery/v1/recommends?channel=and-d10&device=android&includeActivity=true&includeSpecial=true&scale=2&version=4.3.44.2" delegate:self];
    
    
    [NetworkHandlerBlock netWorkingWithURL:@"http://mobile.ximalaya.com/mobile/discovery/v1/recommends?channel=and-d10&device=android&includeActivity=true&includeSpecial=true&scale=2&version=4.3.44.2" completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        
        self.arrForDataOfCollectionViewOne = [NSMutableArray array];
        
        NSDictionary *dicTemp = [NSDictionary dictionaryWithDictionary:result];
        NSMutableArray *arrTemp = [NSMutableArray array];
        
        
        
        if ([[dicTemp allKeys] containsObject:@"focusImages"] ) {
            
            
            [arrTemp addObject:[dicTemp objectForKey:@"focusImages"]];
            [arrTemp addObject:[dicTemp objectForKey:@"editorRecommendAlbums"]];
            [arrTemp addObject:[dicTemp objectForKey:@"hotRecommends"]];
            
            for (NSDictionary *dic in arrTemp) {
                
                if ([[dic objectForKey:@"title"] isEqualToString:@"小编推荐"]) {
                    ModelForData *model = [[ModelForData alloc]init];
                    model.arrForXiaoBian = [NSMutableArray arrayWithArray:[dic objectForKey:@"list"]];
                    [self.arrForDataOfCollectionViewOne addObject:model];
                    [model release];
                }
                
                if ([[dic objectForKey:@"title"] isEqualToString:@"热门推荐"]) {
                    
                    // 最外层list,几乎包含所有信息.(包含外层大字典的信息,更包括大字典中三个小字典列表的信息)
                    NSArray *arrTemp = [NSArray arrayWithArray:[dic objectForKey:@"list"]];
                    
                    for (NSDictionary *dic in arrTemp) {
                        ModelForData *model = [[ModelForData alloc]init];
                        [model setValuesForKeysWithDictionary:dic];
                        
                        // 里层的list数组,包含三个小字典的信息.
                        model.arrForHotRecommends = [NSMutableArray arrayWithArray:[dic objectForKey:@"list"]];
                        
                        [self.arrForDataOfCollectionViewOne addObject:model];
                        [model release];
                    }
                }
                
                if ([[dic objectForKey:@"title"] isEqualToString:@"焦点图"]) {
                    ModelForData *model = [[ModelForData alloc]init];
                    model.arrForPic = [NSMutableArray arrayWithArray:[dic objectForKey:@"list"]];
                    [self.arrForDataOfCollectionViewOne addObject:model];
                    [model release];
                }
            }
        }
     
        // 数据解析完毕之后再将collection刷新一遍.
        [self.collection reloadData];
    }];
}

- (void)handlerDidComplete:(id)result {

    // 数据结构的处理.总结两种方法.
    // 第一种,从最外层开始建model,每一层的信息用一个model储存(KVC).当创建界面时也是从外往里铺,这时从外到里的界面相继对应相应的model(优点,将数据全盘接受过来了,以及铺UITableView 或者UIColletionView时,可以在其相应的Cell中嵌套UITableView,这层数据便是第二层的model了,避免在第二种方法中利用嵌套时,会导致在UITableView中只能通过For循环,或者单个的控件的重复创建)  (理解这个每层的model和对应每层的Cell的平行且一一对应的关系,  便于封装,cell的重用性强)(推荐)
    // 第二种方法, 把创建的相同Cell个数对应的数据,创建相同个数的model储存起来,其它数据,在这个model类中创建数组属性,将对应的数据储存到数组当中,注意数组的初始化.(优点:用到什么储存什么,全局只有一个model, 缺点:有些界面信息不能全面反映出来(用KVC的方法能方法便的得到字典或数组中的全部信息))
    
    // 数组初始化.
    self.arrForDataOfCollectionViewOne = [NSMutableArray array];

    NSDictionary *dicTemp = [NSDictionary dictionaryWithDictionary:result];
    NSMutableArray *arrTemp = [NSMutableArray array];
    
    if ([[dicTemp allKeys] containsObject:@"focusImages"] ) {
        
        
    [arrTemp addObject:[dicTemp objectForKey:@"focusImages"]];
    [arrTemp addObject:[dicTemp objectForKey:@"editorRecommendAlbums"]];
    [arrTemp addObject:[dicTemp objectForKey:@"hotRecommends"]];

    for (NSDictionary *dic in arrTemp) {

        if ([[dic objectForKey:@"title"] isEqualToString:@"小编推荐"]) {
            ModelForData *model = [[ModelForData alloc]init];
            model.arrForXiaoBian = [NSMutableArray arrayWithArray:[dic objectForKey:@"list"]];
            [self.arrForDataOfCollectionViewOne addObject:model];
            [model release];
        }
    
        if ([[dic objectForKey:@"title"] isEqualToString:@"热门推荐"]) {
            
        // 最外层list,几乎包含所有信息.(包含外层大字典的信息,更包括大字典中三个小字典列表的信息)
            NSArray *arrTemp = [NSArray arrayWithArray:[dic objectForKey:@"list"]];
   
            for (NSDictionary *dic in arrTemp) {
                ModelForData *model = [[ModelForData alloc]init];
                [model setValuesForKeysWithDictionary:dic];
                
                // 里层的list数组,包含三个小字典的信息.
                model.arrForHotRecommends = [NSMutableArray arrayWithArray:[dic objectForKey:@"list"]];
       
                [self.arrForDataOfCollectionViewOne addObject:model];
                [model release];
            }
        }
        
        if ([[dic objectForKey:@"title"] isEqualToString:@"焦点图"]) {
            ModelForData *model = [[ModelForData alloc]init];
            model.arrForPic = [NSMutableArray arrayWithArray:[dic objectForKey:@"list"]];
            [self.arrForDataOfCollectionViewOne addObject:model];
            [model release];
        }
    }
        
    }
    
    // 数据解析完毕之后再将collection刷新一遍.
    [self.collection reloadData];
}

#pragma mark ** 采用Block模式回调.
- (void)handleDataForCollectionViewTwo  {
    self.arrForDataOfCollectionViewTwo = [NSMutableArray array];
    
    [NetworkHandlerBlock netWorkingWithURL:@"http://mobile.ximalaya.com/mobile/discovery/v1/categories?device=android&picVersion=11&scale=2" completeHandle:^(NSURLResponse *response, NSData *data, id result) {

        NSArray *arr = [result objectForKey:@"list"];
        for (NSDictionary *dic in arr) {
            ModelForCollectionViewTwo *model = [[ModelForCollectionViewTwo alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.arrForDataOfCollectionViewTwo addObject:model];
        }
        [self.collection reloadData];
    }];
}

- (void)handleDataForCollectionViewFour {
    
    self.arrForDataOfCollectionViewFour = [NSMutableArray array];
    [NetworkHandlerBlock netWorkingWithURL:@"http://mobile.ximalaya.com/mobile/discovery/v2/rankingList/group?channel=and-d10&device=android&includeActivity=true&includeSpecial=true&scale=2&version=4.3.44.2" completeHandle:^(NSURLResponse *response, NSData *data, id result) {
        
        
        // 取出焦点图中的值.
        NSDictionary *dicTemp = [result objectForKey:@"focusImages"];
        NSArray *arrTemp = [dicTemp objectForKey:@"list"];
        for (NSDictionary *dic in arrTemp) {
            ModelForCollectionFour *model = [[ModelForCollectionFour alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.arrForDataOfCollectionViewFour addObject:model];
            [model release];
        }
        
        NSArray *arrTempDatas = [result objectForKey:@"datas"];
        
        for (NSDictionary *dic in arrTempDatas) {

                NSArray *arr1 = [dic objectForKey:@"list"];
                for (NSDictionary *dic in arr1) {
                    ModelForCollectionFour *model = [[ModelForCollectionFour alloc]init];
                    [model setValuesForKeysWithDictionary:dic];
                    [self.arrForDataOfCollectionViewFour addObject:model];
            }
            }

        [self.collection reloadData];
    }];
}

- (void)handleDataForCollectionViewFive {

    self.arrForDataOfCollectionViewFive = [NSMutableArray array];
    [NetworkHandlerBlock netWorkingWithURL:@"http://mobile.ximalaya.com/m/explore_user_index?device=android&page=1" completeHandle:^(NSURLResponse *response, NSData *data, id result) {
    
       
            NSArray *arrTemp = [result objectForKey:@"list"];
        for (NSDictionary *dic in arrTemp) {
            ModelForCollectionViewFive *model = [[ModelForCollectionViewFive alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            NSArray *arrTempForDic = [dic objectForKey:@"list"];
            for (NSDictionary *dic in arrTempForDic) {
                [model.arrForSmallLogo addObject:dic];
            }
            [self.arrForDataOfCollectionViewFive addObject:model];
            [model release];
        }
    }];
    
    [NetworkHandlerBlock netWorkingWithURL:@"http://mobile.ximalaya.com/m/explore_user_index?device=android&page=2" completeHandle:^(NSURLResponse *response, NSData *data, id result) {
       
            NSArray *arrTemp = [result objectForKey:@"list"];
        for (NSDictionary *dic in arrTemp) {
            ModelForCollectionViewFive *model = [[ModelForCollectionViewFive alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            NSArray *arrTempForDic = [dic objectForKey:@"list"];
            for (NSDictionary *dic in arrTempForDic) {
                [model.arrForSmallLogo addObject:dic];
            }
            [self.arrForDataOfCollectionViewFive addObject:model];
            [model release];
        }
    }];
    
    [NetworkHandlerBlock netWorkingWithURL:@"http://mobile.ximalaya.com/m/explore_user_index?device=android&page=3" completeHandle:^(NSURLResponse *response, NSData *data, id result) {

        NSArray *arrTemp = [result objectForKey:@"list"];
        for (NSDictionary *dic in arrTemp) {
            ModelForCollectionViewFive *model = [[ModelForCollectionViewFive alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            NSArray *arrTempForDic = [dic objectForKey:@"list"];
            for (NSDictionary *dic in arrTempForDic) {
                [model.arrForSmallLogo addObject:dic];
            }
            [self.arrForDataOfCollectionViewFive addObject:model];
            [model release];
        }
    }];
    
    [self.collection reloadData];
}

#pragma mark 首页整体布局
- (void)createTitleView     {
    
    NSArray *arr = @[@"推荐",@"分类",@"榜单",@"主播"];
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, 50)];
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    for (int i = 0; i  < 4; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(WIDTH / 4 * i, 0, WIDTH / 4, 50);
        [view addSubview:button];
        [button setTitle:arr[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(handleAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    [view release];
}

- (void)createRedLine       {
    self.viewForRedLine = [[UIView alloc]initWithFrame:CGRectMake(0, 64 + 50, WIDTH / 4, 3)];
    self.viewForRedLine.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.viewForRedLine];
    [_viewForRedLine release];
}

- (void)creatCollectionView {

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    
    flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT - 117 - 49);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    
    self.collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 64 + 50 + 3, WIDTH, HEIGHT - 117 - 49) collectionViewLayout:flowLayout];
    [self.view addSubview:self.collection];
    self.collection.backgroundColor = [UIColor whiteColor];
    self.collection.pagingEnabled = YES;
    self.collection.dataSource = self;
    self.collection.delegate = self;
    
    [self.collection registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"poolForCollectionViewCellOne"];
    
    [self.collection registerClass:[CollectionCellTwo class] forCellWithReuseIdentifier:@"poolForCollectionViewCellTwo"];
    
    [self.collection registerClass:[CollectionCellFour class] forCellWithReuseIdentifier:@"poolForCollectionViewCellFour"];
    
    [self.collection registerClass:[CollectionCellFive class] forCellWithReuseIdentifier:@"poolForCollectionViewCellFive"];
    
    [flowLayout release];
    [self.collection release];
}

#pragma mark collectionView DataSourece 
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    return 4;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.item == 0) {
        
        CollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolForCollectionViewCellOne" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        
    if (self.arrForDataOfCollectionViewOne.count != 0) {
            cell.arrForTableViewOne = [NSMutableArray arrayWithArray:self.arrForDataOfCollectionViewOne];
            //   [cell.tableView reloadData];(要么重写setter方法,或者设置tableView属性.)
            [cell.tableView reloadData];
        }
        return cell;
    }
    else if (indexPath.item == 1) {
        
        CollectionCellTwo *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolForCollectionViewCellTwo" forIndexPath:indexPath];

        // 数据传值.
    if (self.arrForDataOfCollectionViewTwo.count != 0 ) {
        cell.arrForCollectionViewTwo = self.arrForDataOfCollectionViewTwo;
        [cell.collection reloadData];  
        }
        return cell;
    }
    
    
    else if (indexPath.item == 2) {
        CollectionCellFour *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolForCollectionViewCellFour" forIndexPath:indexPath];
        
    if (self.arrForDataOfCollectionViewFour.count != 0) {
            cell.arrForCollectionViewFour = self.arrForDataOfCollectionViewFour;
        }
        
        cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.f  green:arc4random() % 256 / 255.f blue:arc4random() % 256/ 255.f alpha:arc4random()% 256 / 255.f] ;
        return cell;
    }
    
    else {
        CollectionCellFive *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"poolForCollectionViewCellFive" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.f  green:arc4random() % 256 / 255.f blue:arc4random() % 256/ 255.f alpha:arc4random()% 256 / 255.f];
        if (self.arrForDataOfCollectionViewFive.count != 0) {
            cell.arrForCollectionViewFive = self.arrForDataOfCollectionViewFive;
        }
        return cell;
    }
}

#pragma mark KVO
- (void)createKVO {

    [self.collection addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:nil];

}

// 观察者VC观察到collectionView的contentOffset发生变化时,调用此方法.
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    
    CGFloat x = [[change objectForKey:@"new"] CGPointValue].x;
    CGFloat redX = x / 4;
    self.viewForRedLine.transform = CGAffineTransformMakeTranslation(redX, 0);
}

@end
